package com.etonenet.etpe.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.etonenet.etpe.exception.EtpeException;
import com.etonenet.etpe.request.PhoneMapRequest;
import com.etonenet.etpe.response.PhoneMapResponse;
import com.etonenet.etpe.service.BatchInfoService;
import com.etonenet.etpe.service.PhoneMapService;
import com.etonenet.etpe.util.PhoneMapStatus;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
@RequestMapping("/interface/phonemap")
public class PhoneMapController {

	private static Logger logger = LoggerFactory.getLogger(PhoneMapController.class);

	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private BatchInfoService batchInfoService;
	@Autowired
	private PhoneMapService phoneMapService;

	/**
	 * 
	 * @param request
	 * @return
	 * @throws EtpeException
	 */
	@RequestMapping(value = "/encode", method = RequestMethod.POST)
	public PhoneMapResponse encode(@RequestBody PhoneMapRequest request, HttpServletRequest req) {

		String remoteAddr = req.getRemoteAddr();
		long batchId = batchInfoService.getBatchId();
		PhoneMapResponse response = new PhoneMapResponse();
		Long spId = null;

		try {
			if (logger.isDebugEnabled()) {
				logger.debug("batchId:{} ip:{} From POST /api/phonemap {} ", batchId, remoteAddr,
						objectMapper.writeValueAsString(request));
			}
			spId = Long.valueOf(request.getSpId());

			// 验证用户权限
			PhoneMapStatus status = phoneMapService.validation(spId, request.getSpPassword(), remoteAddr,
					request.getPhones().size());
			if (status != PhoneMapStatus.CODE_200) {
				response.setPhoneMapStatus(status);
				return response;
			}

			// 查询加密号码
			List<String> encodedPhoneList = phoneMapService.encode(request.getPhones(), batchId, spId);

			// 返回结果
			response.setPhoneMapStatus(PhoneMapStatus.CODE_200);
			response.setPhones(encodedPhoneList);
			return response;
		} catch (Exception e) {
			logger.error("batchId:{} {}", batchId, ExceptionUtils.getStackTrace(e));
			response.setPhoneMapStatus(PhoneMapStatus.CODE_400);
			return response;
		} finally {
			// 记录批次信息
			if (logger.isDebugEnabled()) {
				try {
					logger.debug("batchId:{} To {}", batchId, objectMapper.writeValueAsString(response));
				} catch (JsonProcessingException e) {
					logger.error("batchId:{} {}", batchId, ExceptionUtils.getStackTrace(e));
				}
			}

			if (spId != null) {
				batchInfoService.log(spId, batchId, Integer.valueOf(response.getCode()));
			}
		}
	}

	@RequestMapping(value = "/batchencode", method = RequestMethod.POST)
	public PhoneMapResponse batchEncode(@RequestBody PhoneMapRequest request, HttpServletRequest req) {

		String remoteAddr = req.getRemoteAddr();
		long batchId = batchInfoService.getBatchId();
		PhoneMapResponse response = new PhoneMapResponse();
		Long spId = null;

		try {
			if (logger.isDebugEnabled()) {
				logger.debug("batchId:{} ip:{} From POST /api/phonemap {} ", batchId, remoteAddr,
						objectMapper.writeValueAsString(request));
			}
			spId = Long.valueOf(request.getSpId());

			// 验证用户权限
			PhoneMapStatus status = phoneMapService.validation(spId, request.getSpPassword(), remoteAddr,
					request.getPhones().size());
			if (status != PhoneMapStatus.CODE_200) {
				response.setPhoneMapStatus(status);
				return response;
			}

			// 查询加密号码
			List<String> encodedPhoneList = phoneMapService.batchEncode(request.getPhones(), batchId, spId);

			// 返回结果
			response.setPhoneMapStatus(PhoneMapStatus.CODE_200);
			response.setPhones(encodedPhoneList);
			return response;
		} catch (Exception e) {
			logger.error("batchId:{} {}", batchId, ExceptionUtils.getStackTrace(e));
			response.setPhoneMapStatus(PhoneMapStatus.CODE_400);
			return response;
		} finally {
			// 记录批次信息
			if (logger.isDebugEnabled()) {
				try {
					logger.debug("batchId:{} To {}", batchId, objectMapper.writeValueAsString(response));
				} catch (JsonProcessingException e) {
					logger.error("batchId:{} {}", batchId, ExceptionUtils.getStackTrace(e));
				}
			}

			if (spId != null) {
				batchInfoService.log(spId, batchId, Integer.valueOf(response.getCode()));
			}
		}
	}

	@ExceptionHandler({ EtpeException.class })
	public PhoneMapResponse exception(EtpeException e) {
		PhoneMapResponse response = new PhoneMapResponse();
		response.setPhoneMapStatus(PhoneMapStatus.CODE_400);
		return response;
	}
}
